package bma.common.netty.handler;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;

import bma.common.langutil.io.InetNetwork;

public class ChannelHandlerIpFilter extends SimpleChannelUpstreamHandler {

	final org.slf4j.Logger log = org.slf4j.LoggerFactory
			.getLogger(ChannelHandlerIpFilter.class);

	private List<InetNetwork> whiteList = new CopyOnWriteArrayList<InetNetwork>();
	private List<InetNetwork> blackList = new CopyOnWriteArrayList<InetNetwork>();

	public void setWhiteList(List<String> whiteList) {
		List<InetNetwork> tmp = new ArrayList<InetNetwork>(whiteList.size());
		for (String s : whiteList) {
			tmp.add(InetNetwork.create(s));
		}
		this.whiteList.addAll(tmp);
	}

	public static List<InetNetwork> create(String s) {
		String[] ips = s.split(",");
		List<InetNetwork> tmp = new ArrayList<InetNetwork>(ips.length);
		for (String ip : ips) {
			tmp.add(InetNetwork.create(ip.trim()));
		}
		return tmp;
	}

	public void setWhiteAddress(String whiteList) {
		if (whiteList == null || whiteList.isEmpty()) {
			return;
		}

		List<InetNetwork> tmp = create(whiteList);
		this.whiteList.addAll(tmp);
	}

	public void replaceWhiteList(List<InetNetwork> list) {
		this.whiteList.clear();
		this.whiteList.addAll(list);
	}

	public List<InetNetwork> queryWhiteList() {
		return new ArrayList<InetNetwork>(whiteList);
	}

	public void setBlackList(List<String> list) {
		List<InetNetwork> tmp = new ArrayList<InetNetwork>(list.size());
		for (String s : list) {
			tmp.add(InetNetwork.create(s));
		}
		this.blackList.addAll(tmp);
	}

	public void setBlackAddress(String blackList) {
		if (blackList == null || blackList.isEmpty()) {
			return;
		}

		List<InetNetwork> tmp = create(blackList);
		this.blackList.addAll(tmp);
	}

	public void replaceBlackList(List<InetNetwork> list) {
		this.blackList.clear();
		this.blackList.addAll(list);
	}

	public List<InetNetwork> queryBlackList() {
		return new ArrayList<InetNetwork>(blackList);
	}

	@Override
	public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e)
			throws Exception {
		SocketAddress addr = ctx.getChannel().getRemoteAddress();
		if (!checkAddress(addr)) {
			ctx.getChannel().close();
			return;
		}
		super.channelConnected(ctx, e);
	}

	public boolean checkAddress(SocketAddress addr) {
		if (addr instanceof InetSocketAddress) {
			InetAddress iaddr = ((InetSocketAddress) addr).getAddress();
			CheckResult cr = getAddressResult(iaddr);
			if (cr.equals(CheckResult.IN_BLACKLIST)) {
				if (log.isWarnEnabled()) {
					log.warn("blacklist address({})", iaddr);
				}
				return false;
			}
			if (cr.equals(CheckResult.NOT_IN_WHITE_LIST)) {
				if (log.isWarnEnabled()) {
					log.warn("not whitelist address({})", iaddr);
				}
				return false;
			}
		}
		if (log.isDebugEnabled()) {
			log.debug("accept address({})", addr);
		}
		return true;
	}

	public enum CheckResult {
		ALL_PASS, IN_BLACKLIST, NOT_IN_BLACKLIST, NOT_IN_WHITE_LIST,
	}

	public CheckResult getAddressResult(InetAddress iaddr) {
		if (!blackList.isEmpty()) {
			for (InetNetwork n : blackList) {
				if (n.isMatch(iaddr)) {
					return CheckResult.IN_BLACKLIST;
				}
			}
		}
		if (!whiteList.isEmpty()) {
			boolean match = false;
			for (InetNetwork n : whiteList) {
				if (n.isMatch(iaddr)) {
					match = true;
					break;
				}
			}
			if (!match) {
				return CheckResult.NOT_IN_WHITE_LIST;
			}
			return CheckResult.ALL_PASS;
		}
		return CheckResult.NOT_IN_BLACKLIST;
	}
}
